using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Application.DTOs;
using SG3L_RAG.Application.Services;
using SG3L_RAG.Domain.Entities;
using System.Security.Claims;
using System.Linq;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IAuthService _authService;
        private readonly GiteeFileUploadService _giteeFileUploadService;

        public UserController(IUserService userService, IAuthService authService, GiteeFileUploadService giteeFileUploadService)
        {
            _userService = userService;
            _authService = authService;
            _giteeFileUploadService = giteeFileUploadService;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] LoginDto loginDto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var result = await _authService.LoginAsync(loginDto);
                if (result == null)
                    return Unauthorized("用户名或密码错误");

                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest($"登录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var result = await _authService.RegisterAsync(registerDto);
                return Created("", result);
            }
            catch (InvalidOperationException ex)
            {
                return Conflict(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest($"注册失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试端点 - 不需要认证
        /// </summary>
        [HttpGet("test")]
        [AllowAnonymous]
        public IActionResult Test()
        {
            return Ok(new { message = "API正常工作", timestamp = DateTime.Now });
        }

        /// <summary>
        /// 获取所有用户信息（需要管理员权限）
        /// </summary>
        [HttpGet]
        [Authorize]
        public async Task<IActionResult> GetAllUsers([FromQuery] int page = 1, [FromQuery] int pageSize = 10, [FromQuery] string? search = null, [FromQuery] string? role = null)
        {
            try
            {
                // 检查当前用户是否为管理员
                var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
                if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var currentUserId))
                    return Unauthorized("无效的用户令牌");

                var isAdmin = await _userService.IsAdminAsync(currentUserId);
                if (!isAdmin)
                    return StatusCode(403, "需要管理员权限");

                var allUsers = await _userService.GetAllAsync();
                
                // 转换为List以便在内存中进行过滤
                var usersList = allUsers.ToList();
                
                // 应用搜索过滤
                IEnumerable<User> filteredUsers = usersList;
                
                if (!string.IsNullOrEmpty(search))
                {
                    filteredUsers = filteredUsers.Where(u => 
                        (u.Username?.Contains(search, StringComparison.OrdinalIgnoreCase) == true) ||
                        (u.Email?.Contains(search, StringComparison.OrdinalIgnoreCase) == true));
                }
                
                if (!string.IsNullOrEmpty(role))
                {
                    filteredUsers = filteredUsers.Where(u => 
                        string.Equals(u.Role, role, StringComparison.OrdinalIgnoreCase));
                }
                
                // 转换为列表并计算总数
                var filteredList = filteredUsers.ToList();
                var totalCount = filteredList.Count;
                
                // 应用分页
                var pagedUsers = filteredList
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(user => new
                    {
                        id = user.Id,
                        username = user.Username,
                        email = user.Email,
                        phoneNumber = user.PhoneNumber,
                        role = user.Role,
                        avatar = user.Avatar,
                        createdAt = user.CreatedAt
                    })
                    .ToList();

                var result = new
                {
                    data = pagedUsers,
                    total = totalCount,
                    page = page,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };

                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        [HttpGet("me")]
        [Authorize]
        public async Task<IActionResult> GetCurrentUser()
        {
            try
            {
                var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
                if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
                    return Unauthorized("无效的用户令牌");

                var user = await _userService.GetByIdAsync(userId);
                if (user == null)
                    return NotFound("用户不存在");

                return Ok(new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    avatar = user.Avatar,
                    role = user.Role,
                    createdAt = user.CreatedAt
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户信息失败: {ex.Message}");
            }
        }
            /// <summary>
            /// 根据邮箱获取用户信息
            /// </summary>
            [HttpGet("email/{email}")]
            [Authorize]
            public async Task<IActionResult> GetByEmail(string email)
            {
                try
                {
                    var user = await _userService.GetByEmailAsync(email);
                    if (user == null)
                        return NotFound($"邮箱 {email} 不存在");

                    return Ok(new
                    {
                        id = user.Id,
                        username = user.Username,
                        email = user.Email,
                        phoneNumber = user.PhoneNumber,
                        role = user.Role,
                        createdAt = user.CreatedAt
                    });
                }
                catch (Exception ex)
                {
                    return BadRequest($"获取用户失败: {ex.Message}");
                }
            }

        /// <summary>
        /// 根据ID获取用户信息
        /// </summary>
        [HttpGet("{id:guid}")]
        [Authorize]
        public async Task<IActionResult> GetById(Guid id)
        {
            try
            {
                var user = await _userService.GetByIdAsync(id);
                if (user == null)
                    return NotFound($"用户 ID {id} 不存在");

                return Ok(new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    role = user.Role,
                    avatar = user.Avatar, // 添加avatar字段
                    createdAt = user.CreatedAt
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据用户名获取用户信息
        /// </summary>
        [HttpGet("by-username/{username}")]
        [Authorize]
        public async Task<IActionResult> GetByUsername(string username)
        {
            try
            {
                var user = await _userService.GetByUsernameAsync(username);
                if (user == null)
                    return NotFound($"用户名 {username} 不存在");

                return Ok(new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    role = user.Role,
                    avatar = user.Avatar, // 添加avatar字段
                    createdAt = user.CreatedAt
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建新用户（仅管理员）
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Create([FromBody] CreateUserDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var user = await _userService.CreateAsync(dto.Username, dto.Password, dto.Email, dto.PhoneNumber, dto.Role);
                
                return CreatedAtAction(nameof(GetById), new { id = user.Id }, new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    role = user.Role,
                    createdAt = user.CreatedAt
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"创建用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建新用户（兼容旧接口，无手机号）
        /// </summary>
        [HttpPost("legacy")]
        public async Task<IActionResult> CreateLegacy([FromBody] CreateUserLegacyDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var user = await _userService.CreateAsync(dto.Username, dto.Password, dto.Email, dto.Role);
                
                return CreatedAtAction(nameof(GetById), new { id = user.Id }, new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    role = user.Role,
                    createdAt = user.CreatedAt
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"创建用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户手机号
        /// </summary>
        [HttpPut("{id:guid}/phone")]
        [Authorize]
        public async Task<IActionResult> UpdatePhoneNumber(Guid id, [FromBody] UpdatePhoneNumberDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                await _userService.UpdatePhoneNumberAsync(id, dto.PhoneNumber);
                return Ok("手机号更新成功");
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest($"更新手机号失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户邮箱
        /// </summary>
        [HttpPut("{id:guid}/email")]
        [Authorize]
        public async Task<IActionResult> UpdateEmail(Guid id, [FromBody] UpdateEmailDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                await _userService.UpdateEmailAsync(id, dto.Email);
                return Ok("邮箱更新成功");
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest($"更新邮箱失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        [HttpPut("{id:guid}/password")]
        [Authorize]
        public async Task<IActionResult> ChangePassword(Guid id, [FromBody] ChangePasswordDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                await _userService.ChangePasswordAsync(id, dto.NewPassword);
                return Ok("密码修改成功");
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest($"修改密码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 上传用户头像到图床
        /// </summary>
        [HttpPost("{id:guid}/avatar/upload")]
        [Authorize]
        public async Task<IActionResult> UploadAvatar(Guid id, IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                    return BadRequest(new { isSuccess = false, message = "请选择要上传的头像文件" });

                // 验证文件类型
                var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp" };
                if (!allowedTypes.Contains(file.ContentType.ToLower()))
                    return BadRequest(new { isSuccess = false, message = "只支持图片文件 (jpg, png, gif, webp)" });

                // 验证文件大小 (2MB)
                if (file.Length > 2 * 1024 * 1024)
                    return BadRequest(new { isSuccess = false, message = "头像文件大小不能超过2MB" });

                // 上传到 Gitee 图床
                var avatarUrl = await _giteeFileUploadService.UploadFileAsync(file, "avatars");
                if (string.IsNullOrEmpty(avatarUrl))
                    return BadRequest(new { isSuccess = false, message = "头像上传失败，请重试" });

                // 更新用户头像 URL
                await _userService.UpdateAvatarAsync(id, avatarUrl);

                return Ok(new { isSuccess = true, data = avatarUrl, message = "头像上传成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { isSuccess = false, message = $"上传头像失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取用户头像URL
        /// </summary>
        [HttpGet("{id:guid}/avatar")]
        [AllowAnonymous]
        public async Task<IActionResult> GetUserAvatar(Guid id)
        {
            try
            {
                var user = await _userService.GetByIdAsync(id);
                if (user == null)
                    return NotFound("用户不存在");

                if (string.IsNullOrEmpty(user.Avatar))
                    return Ok(new { avatarUrl = "" });

                return Ok(new { avatarUrl = user.Avatar });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取头像失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户头像URL
        /// </summary>
        [HttpGet("me/avatar")]
        [Authorize]
        public async Task<IActionResult> GetCurrentUserAvatar()
        {
            try
            {
                var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
                if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
                    return Unauthorized("无效的用户令牌");

                var user = await _userService.GetByIdAsync(userId);
                if (user == null)
                    return NotFound("用户不存在");

                if (string.IsNullOrEmpty(user.Avatar))
                    return Ok(new { avatarUrl = "" });

                return Ok(new { avatarUrl = user.Avatar });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取头像失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户头像URL（直接设置URL）
        /// </summary>
        [HttpPut("{id:guid}/avatar")]
        [Authorize]
        public async Task<IActionResult> UpdateAvatar(Guid id, [FromBody] UpdateAvatarDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                await _userService.UpdateAvatarAsync(id, dto.Avatar);
                return Ok("头像更新成功");
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest($"更新头像失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证用户密码
        /// </summary>
        [HttpPost("{id:guid}/check-password")]
        [Authorize]
        public async Task<IActionResult> CheckPassword(Guid id, [FromBody] CheckPasswordDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var result = await _userService.CheckPasswordAsync(id, dto.Password);
                return Ok(new { isValid = result });
            }
            catch (Exception ex)
            {
                return BadRequest($"验证密码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证用户凭据（用户名+密码）
        /// </summary>
        [HttpPost("validate-credentials")]
        [AllowAnonymous]
        public async Task<IActionResult> ValidateCredentials([FromBody] ValidateCredentialsDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var result = await _userService.ValidateCredentialsAsync(dto.Username, dto.Password);
                return Ok(new { isValid = result });
            }
            catch (Exception ex)
            {
                return BadRequest($"验证凭据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证用户身份信息（用于忘记密码流程）
        /// </summary>
        [HttpPost("verify-identity")]
        [AllowAnonymous]
        public async Task<IActionResult> VerifyIdentity([FromBody] VerifyIdentityDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var user = await _userService.GetByUsernameAsync(dto.Username);
                if (user == null)
                    return NotFound("用户不存在");

                // 验证邮箱或手机号是否匹配
                bool isValid = false;
                if (!string.IsNullOrEmpty(dto.Email))
                {
                    isValid = user.Email?.Equals(dto.Email, StringComparison.OrdinalIgnoreCase) == true;
                }
                else if (!string.IsNullOrEmpty(dto.PhoneNumber))
                {
                    isValid = user.PhoneNumber?.Equals(dto.PhoneNumber) == true;
                }

                if (!isValid)
                    return BadRequest("用户名与邮箱/手机号不匹配");

                return Ok(new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    phoneNumber = user.PhoneNumber,
                    isValid = true
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"身份验证失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 重置密码（用于忘记密码流程）
        /// </summary>
        [HttpPost("reset-password")]
        [AllowAnonymous]
        public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                // 简单验证码验证（实际项目中应该使用更安全的验证机制）
                if (dto.VerifyCode != "123456")
                    return BadRequest("验证码错误");

                await _userService.ChangePasswordAsync(dto.UserId, dto.NewPassword);
                return Ok("密码重置成功");
            }
            catch (Exception ex)
            {
                return BadRequest($"重置密码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查用户是否为管理员
        /// </summary>
        [HttpGet("{id:guid}/is-admin")]
        [Authorize]
        public async Task<IActionResult> IsAdmin(Guid id)
        {
            try
            {
                var result = await _userService.IsAdminAsync(id);
                return Ok(new { isAdmin = result });
            }
            catch (Exception ex)
            {
                return BadRequest($"检查管理员权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查用户是否为普通用户
        /// </summary>
        [HttpGet("{id:guid}/is-normal-user")]
        [Authorize]
        public async Task<IActionResult> IsNormalUser(Guid id)
        {
            try
            {
                var result = await _userService.IsNormalUserAsync(id);
                return Ok(new { isNormalUser = result });
            }
            catch (Exception ex)
            {
                return BadRequest($"检查用户权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查用户是否对文档有特定权限
        /// </summary>
        [HttpGet("{userId:guid}/has-permission/{documentId:guid}/{permissionType}")]
        [Authorize]
        public async Task<IActionResult> HasPermission(Guid userId, Guid documentId, string permissionType)
        {
            try
            {
                var result = await _userService.HasPermissionAsync(userId, documentId, permissionType);
                return Ok(new { hasPermission = result });
            }
            catch (Exception ex)
            {
                return BadRequest($"检查权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据角色获取用户列表
        /// </summary>
        [HttpGet("by-role/{role}")]
        [Authorize]
        public async Task<IActionResult> GetUsersByRole(string role)
        {
            try
            {
                var users = await _userService.GetUsersByRoleAsync(role);
                var result = users.Select(u => new
                {
                    id = u.Id,
                    username = u.Username,
                    email = u.Email,
                    phoneNumber = u.PhoneNumber,
                    role = u.Role,
                    createdAt = u.CreatedAt
                });

                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取角色用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的文档列表
        /// </summary>
        [HttpGet("{id:guid}/documents")]
        [Authorize]
        public async Task<IActionResult> GetUserDocuments(Guid id)
        {
            try
            {
                var documents = await _userService.GetUserDocumentsAsync(id);
                return Ok(documents);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的会话列表
        /// </summary>
        [HttpGet("{id:guid}/conversations")]
        [Authorize]
        public async Task<IActionResult> GetUserConversations(Guid id)
        {
            try
            {
                var conversations = await _userService.GetUserConversationsAsync(id);
                return Ok(conversations);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户会话失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的权限列表
        /// </summary>
        [HttpGet("{id:guid}/permissions")]
        [Authorize]
        public async Task<IActionResult> GetUserPermissions(Guid id)
        {
            try
            {
                var permissions = await _userService.GetUserPermissionsAsync(id);
                return Ok(permissions);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户信息（仅管理员）
        /// </summary>
        [HttpPut("update/{id:guid}")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UpdateUserDto updateUserDto)
        {
            try
            {
                var updatedUser = await _userService.UpdateUserAsync(id, updateUserDto);
                return Ok(new { message = "用户信息更新成功", user = updatedUser });
            }
            catch (Exception ex)
            {
                return BadRequest($"更新用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除用户（仅管理员）
        /// </summary>
        [HttpDelete("{id:guid}")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> Delete(Guid id)
        {
            try
            {
                await _userService.DeleteAsync(id);
                return Ok("用户删除成功");
            }
            catch (Exception ex)
            {
                return BadRequest($"删除用户失败: {ex.Message}");
            }
        }
    }
}
